//
//  SortLinesNavigator.swift
//  xcodesort-es
//
//  Created by 赵梁 on 2021/5/26.
//

import Foundation
import XcodeKit

struct SortLinesNavigator: Navigator {
    var title: String = "Sort Lines"
    
    func navigate(invocation: XCSourceEditorCommandInvocation) {
        print(invocation)
        
        guard let first = invocation.buffer.selections.firstObject as? XCSourceTextRange else { return }
        let start = Int(first.start.line)
        let end = Int(first.end.line)
        let range = start...end
        let indexSet = IndexSet(integersIn: range)
        guard var lines: [String] = invocation.buffer.lines.objects(at: indexSet) as? [String] else { return }
        
        lines = lines.sorted { a, b in
            return a.compare(b) == .orderedAscending
        }
        invocation.buffer.lines.replaceObjects(at: indexSet, with: lines)
        print(invocation.buffer.lines)
    }
}
